package pl.perseus.service.user;

import lombok.Data;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.perseus.dao.IUserDao;
import pl.perseus.model.Rach;
import pl.perseus.model.User;
import pl.perseus.service.exception.LoginException;

@Data
@Service
@Transactional
public class UserService implements IUserService{

	@Autowired
	private IUserDao userDao;
	
	@Override
	public void logIn(String login, String passwd) throws LoginException{
		User u = userDao.selectByLoginUser(login);
		if(u == null || !u.getPassword().equals(DigestUtils.md5Hex(passwd))) throw new LoginException();
	}
	
	@Override
	public User selectUserByLogin(String login){
		return userDao.selectByLoginUser(login);
	}
	
	@Override
	public User insertUser(User u){
		u.setActive(true);
		u.setPassword(DigestUtils.md5Hex(u.getPassword()));
		return userDao.insertUser(u);
	}
	
	@Override
	public User updateUser(User u){
		u.setActive(true);
		u.setPassword(DigestUtils.md5Hex(u.getPassword()));
		return userDao.updateUser(u);
	}
	
	@Override
	public User getByRach(Rach rach){
		return userDao.getUserForRach(rach);
	}
	
}
